package com.neuedu.jdboot.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.neuedu.jdboot.bean.Admin;
import com.neuedu.jdboot.bean.Privilege;
import com.neuedu.jdboot.service.AdminService;
import com.neuedu.jdboot.service.RoleService;
import com.neuedu.jdboot.util.PasswordUtils;

@Controller
@RequestMapping("/sys")
public class LoginController {
	private Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private AdminService adminService;

	@Autowired
	private RoleService roleService;

	@GetMapping("login")
	public String login() {

		return "admin/login";
	}

	@PostMapping("login")
	public String doLogin(Admin admin, String validate, HttpServletRequest request) {

		String rand = (String) request.getSession().getAttribute("rand");
		logger.info(rand);
		// 先检查验证码
		if (rand != null && rand.equalsIgnoreCase(validate)) {
			// 再验证账号和密码
			Admin temp = adminService.login(admin.getAccount());
			if (temp != null) {
				if (PasswordUtils.matches(temp.getSalt(), admin.getPassword(), temp.getPassword())) {
					if (temp != null) {
						List<Privilege> list = roleService.findByRole(temp.getId());
						temp.getRole().setPrivileges(list);
					}
					// 使用 session进行会话跟踪
					request.getSession().setAttribute("LOGIN_USER", temp);
					return "redirect:/sys/index";
				}
			}
		}
		// 登录失败，返回login控制器
		return "redirect:/sys/login";
	}

	@GetMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/sys/login";
	}
}
